package one.bugu.android.demon.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Picture;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.common.util.*;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;
import com.umeng.socialize.UMShareAPI;

import one.bugu.android.demon.R;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseActivity;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.constant.ShareConfig;
import one.bugu.android.demon.ui.activity.snatch.SnatchDetailsActivty;
import one.bugu.android.demon.ui.widget.BaseTopBarView;
import one.bugu.android.demon.ui.widget.XWebView;
import one.bugu.android.demon.util.ImageUtils;
import one.bugu.android.demon.util.ImgHelper;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;
import one.bugu.android.demon.util.ShareDialogUtils;
import one.bugu.android.demon.util.ShareImageUtils;
import one.bugu.android.demon.util.ShareUtils;
import one.bugu.android.demon.util.StatusBarUtils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: LangK
 * Date: 2017/11/29
 * Time: 16:17
 * Description:网页界面
 */
@LKContentView(R.layout.activity_web)
public class WebActivity extends MyBaseActivity implements XWebView.OnWebListener {

    public static final String TITLEVISITY = "titleVisity";
    public static final String TITLE = "title";
    public static final String URL = "url";
    /**
     * 订单详情是使用
     */
    public static final String ORDERNO = "orderNo";
    public static final String PERIODID = "periodId";

    private final int MAX_PROGESS = 100;
    /**
     * webview
     */
    @LKInjectView(R.id.xweb_web)
    private XWebView webView;
    /**
     * topBar
     */
    @LKInjectView(R.id.btbv_web_page)
    private BaseTopBarView baseTopBarView;

    /**
     * 页面加载进度条
     */
    @LKInjectView(R.id.progress_bar_web)
    private ProgressBar progressBar;

    private String urls;

    private String token;
    /**
     * 图片存放路径
     */
    private String imageFilePath;

    private String fileName;

    private boolean goToRequestShare = false;
    private String orderNo;
    private int periodId;

    @Override
    protected void initView() {
        super.initView();
        progressBar.setMax(MAX_PROGESS);
        progressBar.setVisibility(View.GONE);
    }

    @Override
    protected void initData() {
        super.initData();
        token = PreferencesUtil.getInstance().getString(WebActivity.this, Constant.TOKEN);
        //设置topBar显示与隐藏
        boolean titleVisity = getIntent().getBooleanExtra(TITLEVISITY, true);
        if (!titleVisity) {
            baseTopBarView.setVisibility(View.GONE);
        }
        //设置页面title
        String title = getIntent().getStringExtra(TITLE);
        if (title != null && !title.isEmpty()) {
            baseTopBarView.setTitle(title);
        }
        //根据页面来源设置不同的标题栏及状态栏
        setTopBarStatus(title);
        baseTopBarView.setRightBtnImageShow(TextUtils.equals(title, "订单详情"));
        orderNo = getIntent().getStringExtra(ORDERNO);
        periodId = getIntent().getIntExtra(PERIODID, 0);
        //获取URL
        urls = getIntent().getStringExtra(URL);
        if (urls != null && !urls.isEmpty()) {
            if (!StringUtil.isEmpty(token)) {
                if (urls.contains("?")) {
                    urls = urls + "&token=" + token;
                } else {
                    urls = urls + "?token=" + token;
                }
            }
            if (!urls.contains("http://") && !urls.contains("https://")) {
                urls = "http://" + urls;
            }
            LogUtil.e("WebActivity load urls: " + urls);
            webView.loadUrl(urls);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();// 生命周期onResume
        //分享回来时请求接口改变分享状态
        if (goToRequestShare) {
            changeShateStatus();
            goToRequestShare = false;
        }

    }

    @Override
    protected void onPause() {
        webView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        webView.destroy();
        super.onDestroy();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        //topBar点击事件
        baseTopBarView.setEventInterface(new BaseTopBarView.EventInterface() {
            @Override
            public void leftOnClick() {
                if (webView != null && webView.canGoBack()) {
                    // 返回前一个页面
                    webView.goBack();
                } else {
                    finish();
                }
            }

            @Override
            public void leftCloseClick() {

            }

            @Override
            public void rightOnClick() {
                String inviteCode = PreferencesUtil.getInstance().getString(WebActivity.this, Constant.INVITE_CODE);
                ShareDialogUtils.getInstance().shareUrl(WebActivity.this, HttpConstant.JOIN_H5_URL + inviteCode,
                        ShareConfig.JOIN_TITLE, ShareConfig.JOIN_CONTENT, ShareConfig.JOIN_IMAGE, false);
            }
        });
        webView.setOnWebListener(this);
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                setNewProgress(newProgress);
            }
        });
    }


    /**
     * 设置进度条进度
     *
     * @param newProgress
     */
    private void setNewProgress(int newProgress) {
        if (newProgress == MAX_PROGESS) {
            hideProgressBar();
            return;
        }
        if (progressBar.getVisibility() == View.GONE) {
            progressBar.setVisibility(View.VISIBLE);
        }
        progressBar.setMax(MAX_PROGESS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            progressBar.setProgress(newProgress, true);
        } else {
            progressBar.setProgress(newProgress);
        }
    }

    /**
     * 隐藏进度条
     */
    private void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    String str = (String) msg.obj;
                    imageFilePath = ShareDialogUtils.getInstance().getImageFile(WebActivity.this);
                    fileName = imageFilePath + "/" + System.currentTimeMillis() + ".jpeg";
                    ImgHelper.generateImage(str, fileName);
                    ShareDialogUtils.getInstance().shareImage(WebActivity.this, fileName);
                    break;
            }
        }
    };

    /**
     * 修改分享状态
     */
    private void changeShateStatus() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("periodId", String.valueOf(periodId));
        LKUtil.getHttpManager().postBody(HttpConstant.CHANGE_SHARE_STATUS, map, mHandler);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler mHandler = new BaseHttpAsycResponceHandler<Object>() {
        @Override
        public void onSuccess(Object o) {
            super.onSuccess(o);
            //调用JS方法去刷新界面
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:sharereturun('" + true + "')");
                }
            });
        }

        @Override
        public void onFailed(int code, String message) {
            super.onFailed(code, message);
            //调用JS方法去刷新界面
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:sharereturun('" + false + "')");
                }
            });
        }

        @Override
        public void onError() {
            super.onError();

        }
    };


    @Override
    public void goBack() {
        finish();
    }

    @Override
    public void closeBySelf() {
        ToastUtils.custom("自己的商品不能购买");
        finish();
    }

    @Override
    public void savePic(String str) {
        if (StringUtil.isEmpty(str)) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionManager.checkFilePermission(WebActivity.this)) {
                return;
            }
        }
        String base64img = str.substring(str.indexOf(",") + 1);

        handler.sendMessage(handler.obtainMessage(0, base64img));
    }

    @Override
    public void shareUrl(String urls) {
        //夺宝中奖分享
        goToRequestShare = true;
        if (!TextUtils.isEmpty(urls)) {
            if (urls.contains("freeregisternew") && urls.contains("code")) {
                //邀请好友 分享
                ShareDialogUtils.getInstance().shareUrl(WebActivity.this, HttpConstant.SHARE_H5_URL + urls,
                        ShareConfig.INVITE_TITLE, ShareConfig.INVITE_CONTENT, ShareConfig.INVITE_IMAGE, false);
            } else if (urls.contains("sharedetail")) {
                //中奖后分享
//                ShareDialogUtils.getInstance().shareUrl(WebActivity.this, HttpConstant.SHARE_H5_URL + urls,
//                        ShareConfig.WIN_TITLE, ShareConfig.WIN_CONTENT, ShareConfig.WIN_IMAGE, true);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ShareImageUtils.getInstance().compShareWebImage(WebActivity.this, webView, baseTopBarView, false);
                    }
                });
            }
        } else {
            Toast.makeText(this, "网络有点慢,请再试一下...", Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 保存图片
     */
    private void saveImage() {
        imageFilePath = ShareDialogUtils.getInstance().getImageFile(this);
        fileName = imageFilePath + "/shar.jpeg";
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_gzhhqrcode);
        ImageUtils.saveImageAndCompress(bitmap, fileName);
        ImageUtils.notifyCarme(WebActivity.this, fileName);
        Toast.makeText(WebActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
            // 返回前一个页面
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private File camereFile;
    private File resizeFile;

    private void saveWeb(String dirName) {
        fileName = dirName + "/邀请码.jpg";
        Bitmap bitmap = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            float scale = webView.getScale();
            int width = webView.getWidth();
            int height = (int) (webView.getContentHeight() * scale + 0.5);
            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            webView.draw(canvas);
        } else {
            Picture picture = webView.capturePicture();
            int width = picture.getWidth();
            int height = picture.getHeight();
            if (width > 0 && height > 0) {
                bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
                Canvas canvas = new Canvas(bitmap);
                picture.draw(canvas);
            }
        }
        if (bitmap == null) {
            LogUtil.e("WebView未获取到Bitmap");
            return;
        }
        ImageUtils.saveImageAndCompress(bitmap, fileName);
        ImageUtils.notifyCarme(WebActivity.this, fileName);
        ShareDialogUtils.getInstance().shareImage(this, fileName);
    }

    /**
     * 设置标题栏及状态栏
     *
     * @param title 标题
     */
    private void setTopBarStatus(String title) {
        switch (title) {
            case "添加客服微信":
            case "关注公众号":
                //设置状态栏
                StatusBarUtils.getInstance().setStatusBar("#5856D0", this, baseTopBarView, true);
                baseTopBarView.setLayoutBGColor(Color.parseColor("#5856D0"));
                baseTopBarView.setLeftBtnImage(R.mipmap.fanhui_wd);
                baseTopBarView.setTitleColor(Color.parseColor("#FFFFFF"));
                break;
            default:
                StatusBarUtils.getInstance().setStatusBar("#FFFFFF", this, baseTopBarView, false);
                baseTopBarView.setLayoutBGColor(Color.parseColor("#FFFFFF"));
                break;
        }
    }
}
